# !/usr/bin/env python
# -*- coding:utf-8 -*-
# @FileName  :jwt_auth.py
# @Time      :2022/5/30 11:56
# @Author    :张志坤

from flask import request, g, current_app
from common.utils.jwt_util import verify_jwt, _generate_token
import redis


# 鉴权
def jwt_authentication():
    """
    验证token
    在获取用户信息前验证前端发起的请求携带的token,是否和后端生成的一样
    """
    g.user_id = None
    g.is_refresh = False
    # 获取请求头中的token
    secret = current_app.config['SECRET_KEY']
    token = request.headers.get('Authorization')
    print('鉴权的token>>>>>>>>', token)
    if token and token.startswith('JWT '):
        payload = verify_jwt(token[4:], secret)
        print('鉴权的payload>>>>>>>', payload)
        if payload:
            # token校验成功  保存到g对象
            g.user_id = payload.get('user_id', None)
            # 判断是否是刷新生成的token   如果取不到  给他个False
            g.is_refresh = payload.get('is_refresh', False)
            print("鉴权中g.is_refresh>>>>>>>>>>>", g.is_refresh)
            """
            当g.is_fresh == false说明token 过期  需要重新生成token
            """
            # 从redis 获取当前用户的token
            rds = redis.Redis()
            rds_token = rds.get("user:%s:token" % g.user_id)
            print('rds_token>>>', rds_token)
            if rds_token:
                if token != rds_token.decode():
                    print('两次token 不一样', rds_token.decode(), '---------------', token)
                    # 此时说明当前用户请求携带的token与Redis中的token不一致
                    return {"message": '没有权限访问', "code": 403}
            else:
                pass
        # else:
        #     g.is_refresh = True
        #     print("鉴权刷新is_refresh", g.is_refresh)
        else:
            # 没有校验通过
            # 也就是token过期
            # 需要生成新的token
            payload_ = {
                "is_refresh": True
            }
            _, refresh_token = _generate_token(payload_, is_refresh=True)
            # 把生成的刷新token重新给请求头中的token
            print("这是在鉴权时原token过期后生成的刷新refresh_token", refresh_token)
            # request.headers['Authorization'] = refresh_token
            try:
                request.headers['Authorization'] = refresh_token
            except Exception as e:
                print("刷新token赋值请求头报错", e)
